<?php

namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\UserCert;
use app\common\library\Sms;
use think\Db;
use think\exception\DbException;

/**
 * Class Account    用户资料管理类
 * @package app\api\controller
 */
class Account  extends Api
{
    protected $noNeedLogin = ['change_password'];
    protected $noNeedRight = '*';

    /**
     * 首页获取用户初始资料
     */
    public function get_index_info()
    {
        $user = $this->auth->getUser();
        //  处理需要的字段
        $needField = ['id','nickname','mobile','is_certification','pay_password'];
        foreach ($needField as $k) $needField[$k] = $k;

        $result = [];   //  要返回的数据
        foreach ($user->getData() as $k=>$v)
        {
            if (isset($needField[$k]))
                $result[$k] = $v;
        }
        $result['pay_password'] = $result['pay_password'] == '' ? '' : 'This Is Pay Password';

        $cert = new UserCert();
        $cert_log = $cert->where('user_id','=',$user->id)->find();
        if ($cert_log)
        {
            $result['is_certification'] = $cert_log->status;
        }
        else
        {
            $result['is_certification'] = config('AuthStatus.NoAuth');
        }

        //  获取用户其他信息
        $user_cert = new UserCert();
        $user_info = $user_cert->where('user_id','=',$user->id)->find();
        if ($user_info)
        {
            $result['wechat']   =  $user_info->wechat;
            $result['alipay']   =  $user_info->alipay;
            $result['bank_card']   =  $user_info->bank_card;
            $result['bank_realname']   =  $user_info->bank_realname;
            $result['bank_address']   =  $user_info->bank_address;
        }

        $this->success('个人资料',$result);
    }

    /**
     * 认证状态
     */
    public function get_auth_status()
    {
        $user = $this->auth->getUser();

        $result = ['img_front' => '','img_back' => '','real_name' => '','id_number' => '','status' => intval($user->is_certification),'reason' => ''];

        $user_auth = new UserCert();
        $user_auth = $user_auth->where('user_id','=',$user->id)->find();
        if ($user_auth)
        {
            $images = explode(',',$user_auth->id_images);

            if (count($images) > 1)
            {
                $result['img_front'] = $images[0];
                $result['img_back'] = $images[1];
            }
            $result['real_name'] = $user_auth->realname;
            $result['id_number'] = $user_auth->id_number ? $user_auth->id_number : '';
            $result['status'] = intval($user_auth->status);
            if ($user_auth->status == config('AuthStatus.Fail'))
            {
                //  审核失败
                $result['reason']   =  intval($user_auth->audit_reason);
            }
        }else
        {
            $result['status'] = intval(config('IsCert.UnCertified'));
        }

        $this->success('用户认证状态',$result);
    }

    /**
     * 修改昵称
     */
    public function change_nickname()
    {
        $user = $this->auth->getUser();

        $result = $this->validate(request()->request(),'Account.changeNickname');
        if ($result !== true) $this->error($result);

        $new_nickname = request()->request('nickname');
        $user->nickname = $new_nickname;
        if ($user->save())
        {
            $this->success('修改成功',['new_nickname' => $user->nickname]);
        }
        else{
            $this->error('昵称无变化');
        }
    }

    /**
     * 修改手机号
     */
    public function change_phone()
    {
        $validate_result = $this->validate($this->request->request(),'Account.change_phone');
        if ($validate_result !== true) $this->error($validate_result);

        $new_phone = $this->request->request('new_phone');
        $old_phone = $this->request->request('old_phone');
        $new_captcha = $this->request->request('new_captcha');
        $old_captcha = $this->request->request('old_captcha');
        $where['delete_time'] = ['eq',''];
        $where['mobile'] = $new_phone;
        $r = db('user')->where($where)->select();
        if($r){
            $this->error('该号码已被注册');
        }
        if (!Sms::check($old_phone,$old_captcha))
        {
            $this->error('原手机号验证码不正确');
        }
        if (!Sms::check($new_phone,$new_captcha))
        {
            $this->error('新手机号验证码不正确');
        }
        
        $user = $this->auth->getUser();
        if ($old_phone != $user->mobile)
        {
            $this->error('原手机号不属于该用户');
        }
        if ($user->username == $user->mobile)
        {
            $user->username = $new_phone;
        }
        /*//  查找用户
        $US = new \app\api\model\User();
        $user = $US->where('mobile','=',$mobile)->find();
        if (!$user)
        {
            $this->error('用户不存在');
        }*/

        //
        $user->mobile = $new_phone;
        if ($user->save())
        {
            $this->success('修改成功',['new_phone' => $new_phone]);
        }
        else
        {
            $this->error('修改失败');
        }

    }

    /**
     * 修改支付密码
     */
    public function change_pay_password(){
        //  验证用户昵称
        $validate_result = $this->validate($this->request->request(),'Account.new_pay_password');
        if ($validate_result !== true) $this->error($validate_result);
        //
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        $new_pay_password = $this->request->request('new_pay_password');
        $verify_pay_password = $this->request->request('verify_pay_password');

        $user = $this->auth->getUser();
        if ($mobile != $user->mobile)
        {
            $this->error('手机号不属于该用户');
        }

        if ($new_pay_password !== $verify_pay_password)
        {
            $this->error('两次密码输入不一致');
        }

        //  验证验证码
        if (!Sms::check($mobile,$captcha))
        {
            if (!config('app_debug') || $captcha != '789456')
            {
                $this->error('验证码不正确');
            }
        }

        /*//  查找用户
        $US = new \app\api\model\User();
        $user = $US->where('mobile','=',$mobile)->find();
        if (!$user)
        {
            $this->error('用户不存在');
        }*/
        //  修改支付密码
        $user->pay_password = $this->auth->getEncryptPassword($new_pay_password,$user->salt);
        if ($user->save())
            $this->success('修改成功');
        else
            $this->error('修改失败');
    }

    /**
     * 修改密码
     * */
    public function change_password(){
        //  验证用户昵称
        $validate_result = $this->validate($this->request->request(),'Account.new_password');
        if ($validate_result !== true) $this->error($validate_result);
        //
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        $new_password = $this->request->request('new_password');
        $verify_password = $this->request->request('verify_password');

        if ($new_password !== $verify_password)
        {
            $this->error('两次密码输入不一致');
        }

        //  验证验证码
        if (!Sms::check($mobile,$captcha))
        {
            if (!config('app_debug') || $captcha != '789456')
            {
                $this->error('验证码不正确');
            }
        }


        //  查找用户
        $US = new \app\api\model\User();
        $user = $US->where('mobile','=',$mobile)->find();
        if (!$user)
        {
            $this->error('用户不存在');
        }

        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($new_password, '', true);
        if ($ret)
        {
            $this->success('密码修改成功');
        }
        else
        {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 修改微信号
     */
    public function change_wechat()
    {
        //  验证字段
        $validate_result = $this->validate($this->request->request(),'Account.wechat');
        if ($validate_result !== true) $this->error($validate_result);

        $wechat = $this->request->request('wechat');
        $type = input('type');
        if($type){
            //手机号
            $phone = input('phone');
            if(empty($phone)){
                $this->error('手机号码不能空');
            }
            //验证码
            $captcha = input('captcha');
            if(empty($captcha)){
                $this->error('验证码不能空');
            }
            //验证验证码
            if (!Sms::check($phone,$captcha))
            {
                $this->error('验证码不正确');
            }
        }
        
        $user = $this->auth->getUser();

        if (UserCert::update(['wechat'    =>  $wechat],['user_id'    =>  $user->id]))
        {
            $this->success('修改成功');
        }
        else
        {
            $this->error('修改失败');
        }
    }

    /**
     * 修改支付宝
     */
    public function change_alipay()
    {
        //  验证字段
        $validate_result = $this->validate($this->request->request(),'Account.alipay');
        if ($validate_result !== true) $this->error($validate_result);

        $alipay = $this->request->request('alipay');
        $type = input('type');
        if($type){
            //手机号
            $phone = input('phone');
            if(empty($phone)){
                $this->error('手机号码不能空');
            }
            //验证码
            $captcha = input('captcha');
            if(empty($captcha)){
                $this->error('验证码不能空');
            }
            //验证验证码
            if (!Sms::check($phone,$captcha))
            {
                $this->error('验证码不正确');
            }
        }
        $user = $this->auth->getUser();

        if (UserCert::update(['alipay'    =>  $alipay],['user_id'    =>  $user->id]))
        {
            $this->success('修改成功');
        }
        else
        {
            $this->error('修改失败');
        }

    }

    /**
     * 修改银行卡信息
     */
    public function change_bank_info()
    {
        //  验证字段
        $validate_result = $this->validate($this->request->request(),'Account.bank');
        if ($validate_result !== true) $this->error($validate_result);


        $bank_card_num = $this->request->request('bank_card_num');
        $bank_realname = $this->request->request('bank_realname');
        $bank_address = $this->request->request('bank_address');
        $type = input('type');
        if($type){
            //手机号
            $phone = input('phone');
            if(empty($phone)){
                $this->error('手机号码不能空');
            }
            //验证码
            $captcha = input('captcha');
            if(empty($captcha)){
                $this->error('验证码不能空');
            }
            //验证验证码
            if (!Sms::check($phone,$captcha))
            {
                $this->error('验证码不正确');
            }
        }
        $user = $this->auth->getUser();


        $update = [
            'bank_address'  =>  $bank_address,
            'bank_card'     =>  $bank_card_num,
            'bank_realname' =>  $bank_realname
        ];

        if (UserCert::update($update,['user_id'    =>  $user->id]))
        {
            $this->success('修改成功');
        }else
        {
            $this->error('修改失败');
        }
    }

    /**
     * 修改头像
     */
    public function change_avatar()
    {
        //  验证字段
        $validate_result = $this->validate($this->request->request(),'Account.avatar');
        if ($validate_result !== true) $this->error($validate_result);

        $avatar = $this->request->request('avatar');

        $user = $this->auth->getUser();
        $user->avatar = $avatar;
        if ($user->save())
        {
            $this->success('头像修改成功',['avatar' => $avatar]);
        }
        else
        {
            $this->error('头像修改失败');
        }
    }

    /**
     * 实名认证
     */
    public function real_name_auth()
    {
        //  验证字段
        $validate_result = $this->validate($this->request->request(),'Account.real_name_auth');
        if ($validate_result !== true) $this->error($validate_result);
        //
        $user = $this->auth->getUser();
        $realname = $this->request->request('real_name');
        $id_number = $this->request->request('id_number');
        $front_path = $this->request->request('IDFront');
        $back_path = $this->request->request('IDBack');

        if (!$front_path || !$back_path) $this->error('请上传完整正反面图片');

        try
        {
            //  判断是否已经上传过
            $cert_log = Db::name('user_certification')
                ->where('user_id','=',$user->id)
                ->find();
            if ($cert_log && $cert_log['status'] > config('AuthStatus.NoAuth'))
            {
                $this->error('你已上传认证，请耐心等待审核');
            }
            //  更新审核
            if ($cert_log['status'] == config('AuthStatus.Fail'))
            {
                $cert_data = [
                    'realname'  =>  $realname,
                    'id_number' =>  $id_number,
                    'id_images' =>  $front_path . ',' . $back_path,
                    'status'    =>  config('AuthStatus.IsAuth'),
                    'upload_time'   =>  time()
                ];
                UserCert::update($cert_data,['user_id' => $user->id]);
                $this->success('更新审核信息成功');
            }else if ($cert_log['status'] == config('AuthStatus.NoAuth'))
            {
                $cert_data = [
                    'realname'  =>  $realname,
                    'id_number' =>  $id_number,
                    'id_images' =>  $front_path . ',' . $back_path,
                    'status'    =>  config('AuthStatus.IsAuth'),
                    'upload_time'   =>  time()
                ];
                UserCert::update($cert_data,['user_id' => $user->id]);
                $this->success('认证上传成功');
            }
            else
            {
                $cert_data = [
                    'user_id'   =>  $user->id,
                    'realname'  =>  $realname,
                    'id_number' =>  $id_number,
                    'id_images' =>  $front_path . ',' . $back_path,
                    'status'    =>  config('AuthStatus.IsAuth'),
                    'upload_time'   =>  time()
                ];
                UserCert::create($cert_data);
                /*$user_cert = new UserCert();
                $user_cert->insert($cert_data);*/
                $this->success('上传成功');
            }
        } catch (DbException $e) {
            $this->error('上传失败');
        }
    }


}